import time
from datetime import datetime, timedelta

from flask import request, render_template, abort, current_app, redirect, url_for, session, g, jsonify

from info import db
from info.constants import USER_COLLECTION_MAX_NEWS, QINIU_DOMIN_PREFIX
from info.models import User, News, Category
from info.modules.admin import admin_blu

# 后台登录
from info.utils.common import user_login_data
from info.utils.img_storage import upload_img
from info.utils.response_code import RET, error_map


@admin_blu.route('/login', methods=['GET', 'POST'])
@user_login_data
def login():
    # get显示
    if request.method == 'GET':
        # 判断是否已登录
        user = g.user.to_dict() if g.user else None
        is_admin = session.get("is_admin")
        if user and is_admin:  # 如果有, 直接进入后台首页
            return render_template("admin/index.html", user=user)

        return render_template("admin/login.html")
    # post登录验证
    username = request.form.get("username")
    password = request.form.get("password")
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="用户名/密码不全")

    # 查询是否有该超级管理员
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询错误")

    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")

    # 有,再比较密码
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="用户名/密码错误")

    # 状态保持
    session["user_id"] = user.id
    session["is_admin"] = True

    # 密码正确才能进入后台
    return redirect(url_for("admin.index"))


# 显示后台首页
@admin_blu.route('/index')
@user_login_data
def index():
    return render_template("admin/index.html", user=g.user.to_dict())


@admin_blu.route('/logout')
def logout():
    # 只需要将session中userid删除即可
    session.pop("user_id", None)
    session.pop("is_admin", None)
    return redirect("/")


# 显示用户数量
@admin_blu.route('/user_count')
def user_count():
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 月新增
    mon_count = 0
    # 新生成 当月1号的日期字符串
    t = time.localtime()
    date_mon_str = "%d-%02d-01" % (t.tm_year, t.tm_mon)
    # 日期字符串转日期对象
    date_mon = datetime.strptime(date_mon_str, "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > date_mon).count()
    except BaseException as e:
        current_app.logger.error(e)

    # 日新增
    day_count = 0
    # 新生成 当月1号的日期字符串
    t = time.localtime()
    date_day_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    # 日期字符串转日期对象
    date_day = datetime.strptime(date_day_str, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time >= date_day).count()
    except BaseException as e:
        current_app.logger.error(e)

    today_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    active_count = []
    active_time = []
    try:
        for i in range(0, 31):
            begin_date = datetime.strptime(date_day_str, "%Y-%m-%d") - timedelta(days=i)
            # end_date = datetime.strptime(date_day_str, "%Y-%m-%d") + timedelta(days=1) - timedelta(days=i)
            end_date = datetime.strptime(date_day_str, "%Y-%m-%d") + timedelta(days=1 - i)

            # 查询一天的登录量
            one_day_count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                              User.last_login < end_date).count()
            active_count.append(one_day_count)
            active_time.append(begin_date.strftime("%Y-%m-%d"))
    except BaseException as e:
        current_app.logger.error(e)

    active_time.reverse()
    active_count.reverse()
    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_time": active_time,
    }

    return render_template("admin/user_count.html", data=data)


# 显示用户列表
@admin_blu.route('/user_list')
def user_list():
    # 获取参数
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    # 查询所有的用户
    user_list = []
    total_pages = 1
    try:
        pn = User.query.filter(User.is_admin == False).paginate(page, USER_COLLECTION_MAX_NEWS)
        user_list = [user.to_admin_dict() for user in pn.items]
        total_pages = pn.pages

    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "total_page": total_pages,
        "user_list": user_list,
        "cur_page": page
    }

    return render_template("admin/user_list.html", data=data)


# 显示待审核新闻列表
@admin_blu.route('/news_review')
def news_review():
    # 获取参数
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    # 查询所有的用户发出的新闻
    news_list = []
    total_pages = 1
    filter_list = [News.user_id != None]
    if keywords:
        filter_list.append(News.title.contains(keywords))
    try:
        pn = News.query.filter(*filter_list).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_pages = pn.pages

    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "total_page": total_pages,
        "news_list": news_list,
        "cur_page": page
    }

    return render_template("admin/news_review.html", data=data)


# 显示待审核新闻详情
@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    # 查询该新闻数据
    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return render_template("admin/news_review_detail.html", data={"errmsg": "没有查询到指定的数据"})

    # 传到模板中
    return render_template("admin/news_review_detail.html", data={"news": news.to_dict()})


# 提交审核
@admin_blu.route('/news_review_action', methods=['POST'])
def news_review_action():
    # 获取参数
    action = request.json.get("action")
    news_id = request.json.get("news_id")

    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news_id = int(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        news = News.query.get(news_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 根据action处理
    if action == "accept":
        news.status = 0
    else:
        news.status = -1
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        news.reason = reason

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 显示版式编辑列表
@admin_blu.route('/news_edit')
def news_edit():
    # 获取参数
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    try:
        page = int(page)
    except BaseException as e:
        current_app.logger.error(e)
        page = 1

    # 查询审核通过的所有新闻
    news_list = []
    total_pages = 1
    filter_list = [News.status != -1, News.status != 1]
    if keywords:
        filter_list.append(News.title.contains(keywords))
    try:
        pn = News.query.filter(*filter_list).paginate(page, USER_COLLECTION_MAX_NEWS)
        news_list = [news.to_review_dict() for news in pn.items]
        total_pages = pn.pages

    except BaseException as e:
        current_app.logger.error(e)

    data = {
        "total_page": total_pages,
        "news_list": news_list,
        "cur_page": page
    }

    return render_template("admin/news_edit.html", data=data)


# 显示版式详情页面
@admin_blu.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    if request.method == "GET":
        # 获取参数
        news_id = request.args.get("news_id")
        try:
            news_id = int(news_id)
        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "参数有误"})

        try:
            news = News.query.get(news_id)
        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "数据库查询失败"})

        if not news:
            return render_template("admin/news_edit_detail.html", data={"errmsg": "指定的新闻未找到"})

        # 查询分类数据
        category_list = []
        try:
            categories = Category.query.all()
            # 查询新闻所在的分类, 添加标记
            for category in categories:
                category_dict = category.to_dict()
                is_selected = False
                if news.category_id == category.id:
                    is_selected = True

                category_dict["is_selected"] = is_selected
                category_list.append(category_dict)

        except BaseException as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", data={"errmsg": "数据查询失败"})

        if len(category_list):
            category_list.pop(0)

        return render_template("admin/news_edit_detail.html",
                               data={"news": news.to_dict(), "categories": category_list})

    # POST处理
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")

    if not all([news_id, title, category_id, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    try:
        news_id = int(news_id)
        category_id = int(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 查询新闻&分类
    try:
        news = News.query.get(news_id)
        category = Category.query.get(category_id)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    if not news or not category:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 修改新闻模型数据
    news.title = title
    news.category_id = category_id
    news.digest = digest
    # 判断是否上传了新图片
    if index_image:
        try:
            img_bytes = index_image.read()
            key = upload_img(img_bytes)
            news.index_image_url = QINIU_DOMIN_PREFIX + key
        except BaseException as e:
            current_app.logger.error(e)
    news.content = content

    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])


# 显示分类列表
@admin_blu.route('/news_type', methods=['GET', 'POST'])
def news_type():
    if request.method == 'GET':
        # 查询所有分类
        categories = []
        try:
            categories = Category.query.all()
        except BaseException as e:
            current_app.logger.error(e)

        if len(categories):
            categories.pop(0)

        return render_template("admin/news_type.html", categories=categories)
    # POST处理
    name = request.json.get("name")
    id = request.json.get("id")
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    if id:  # 修改分类
        try:
            id = int(id)
            category = Category.query.get(id)
        except BaseException as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
        
        category.name = name
        
    else:  # 新增分类
        new_category = Category()
        new_category.name = name
        db.session.add(new_category)
        
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
